<template>
  <div>
    <a-card>
      <a-spin :spinning="spinning" size="large">
        <div style="display: flex">
          <div class="edit-title">
            <a-anchor :affix="false" :getContainer="gerGood" @click="anchorClick" :bounds="300">
              <a-anchor-link :href="item.herf" :title="item.title" class="handle-item" v-for="(item, index) in informationlist" :key="index" />
            </a-anchor>
          </div>
          <!-- <ImgUpload :uploadParams="getUpload()" :isMove="false" :isMultiple="true" @fileChange="e => imgChange(e)" :fileSize="10" :number="1" :accept="'image/*'"></ImgUpload> -->
          <div style="width: 100%; height: 75vh">
            <div style="height: calc(100% - 40px); overflow-y: auto; margin-top: 16px" id="goods">
              <a-form-model ref="ruleForm" :model="form" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol" style="width: 100%; margin-bottom: 100px">
                <div id="components">
                  <h1>基本信息</h1>
                  <a-form-model-item ref="name" label="标题" prop="name">
                    <a-input
                      class="current"
                      placeholder="请输入标题，限50字"
                      v-model.trim="form.name"
                      @blur="
                        () => {
                          $refs.name.onFieldBlur()
                        }
                      "
                    />
                  </a-form-model-item>
                  <a-form-model-item label="介绍" prop="content">
                    <a-input v-model="form.content" placeholder="请输入素材介绍，限200字" type="textarea" class="current" />
                  </a-form-model-item>
                  <a-form-model-item label="发布方" prop="publisherId">
                    <a-select v-model="form.publisherId" placeholder="发布方" class="current">
                      <a-select-option v-for="(item, index) in publisher" :key="index" :value="item.key">{{ item.value }}</a-select-option>
                    </a-select>
                  </a-form-model-item>
                  <a-form-model-item label="分类" prop="cation">
                    <div style="display: flex">
                      <a-select v-model="form.classification" placeholder="请选择" class="current" style="margin-right: 24px" @change="handleProvinceChange">
                        <a-select-option v-for="item in classifyList" :key="item.code" :value="item.code">{{ item.name }}</a-select-option>
                      </a-select>
                      <a-select v-model="form.cation" placeholder="请选择" class="current">
                        <a-select-option v-for="item in copyList" :key="item.code" :value="item.code">{{ item.name }}</a-select-option>
                      </a-select>
                    </div>
                  </a-form-model-item>
                  <a-form-model-item label="适用品牌" required>
                    <template v-for="tag in tags">
                      <a-checkable-tag :key="tag.key" :checked="brandId.indexOf(tag.key) > -1" @change="checked => handleChange(tag.key, checked)">
                        {{ tag.value }}
                      </a-checkable-tag>
                    </template>
                  </a-form-model-item>
                </div>
                <a-divider dashed />
                <div id="components-throw">
                  <h1>投放信息</h1>
                  <a-form-model-item label="投放门店" prop="storeType">
                    <a-radio-group v-model="form.storeType">
                      <a-radio value="1"> 条件筛选 </a-radio>
                      <a-radio value="2"> 选择门店包 </a-radio>
                    </a-radio-group>
                  </a-form-model-item>
                  <a-form-model-item v-if="form.storeType == 2" style="margin-left: 120px">
                    <a-select v-model="form.storePkgId" placeholder="选择门店包,可输入名字搜索" class="current" show-search :filter-option="filterOption">
                      <a-select-option v-for="(item, index) in storeList" :key="index" :value="item.packageId">{{ item.storeName }}</a-select-option>
                    </a-select>
                  </a-form-model-item>
                  <a-form-model-item label="可见渠道" prop="putChannel" v-if="form.storeType == 1">
                    <a-checkbox-group v-model="form.putChannel" @change="onChange">
                      <a-checkbox value="2" name="type"> 直营 </a-checkbox>
                      <a-checkbox value="1" name="type"> 经销 </a-checkbox>
                      <span class="edit-font">如不希望某一渠道看见该素材，请取消勾选</span>
                    </a-checkbox-group>
                  </a-form-model-item>
                  <a-form-model-item label="不可见门店" v-if="form.storeType == 1">
                    <a-checkbox-group v-model="form.putStoreType">
                      <a-checkbox :value="item.key" v-for="(item, index) in information.notPutStoreTypeMap" :key="index"> {{ item.value }} </a-checkbox>
                      <span class="edit-font">如不希望某类门店看见该素材，请勾选</span>
                    </a-checkbox-group>
                  </a-form-model-item>
                  <a-form-model-item label="投放开始时间" prop="putAwayType">
                    <a-radio-group v-model="form.putAwayType">
                      <a-radio value="1"> 立即投放 </a-radio>
                      <a-radio value="3"> 指定时间 </a-radio>
                    </a-radio-group>
                  </a-form-model-item>

                  <a-date-picker v-if="form.putAwayType == 3" @change="onChangeSTime" style="margin-left: 120px" showTime valueFormat="YYYY-MM-DD HH" v-model="form.putAwayTime" />
                  <a-form-model-item label="投放结束时间" prop="finishTime">
                    <a-radio-group v-model="form.finishTime">
                      <a-radio value="1"> 永久有效 </a-radio>
                      <a-radio value="2"> 指定时间 </a-radio>
                    </a-radio-group>
                  </a-form-model-item>
                  <a-date-picker v-if="form.finishTime == 2" @change="onChangeETime" style="margin-left: 120px" showTime valueFormat="YYYY-MM-DD HH" v-model="form.putAwayEndTime" />
                </div>
                <a-divider dashed />
                <div id="components-anchor">
                  <h1>上传图片</h1>
                  <a-form-model-item label="海报图">
                    <JImageUpload
                      :uploadParams="getUploadParams()"
                      :isMultiple="true"
                      :fileSize="10"
                      :number="20"
                      :accept="'image/*'"
                      @fileChange="fileImageChange"
                      v-model="backgroundImage"
                    ></JImageUpload>
                    <div class="upload__tip" style="line-height: 16px">图片/视频至少上传一个，图片建议尺寸 900x1200px，小于2mb，格式jpg、png，建议9张。</div>
                  </a-form-model-item>
                  <a-form-model-item label="效果视频" prop="videoList">
                    <JImageUpload
                      :uploadParams="getUploadParams()"
                      :isMultiple="false"
                      :fileSize="300"
                      :number="1"
                      :accept="'video/*'"
                      @fileChange="fileVideoChange"
                      v-model="videoList"
                    ></JImageUpload>
                    <div class="upload__tip" style="line-height: 16px">视频限制一个，大小300MB</div>
                  </a-form-model-item>
                  <a-form-model-item label="是否生成海报" prop="shareState">
                    <a-radio-group v-model="form.shareState">
                      <a-radio value="3"> 使用版权 <span style="color: #aaaaaa">（明星达人等时效性素材，到期自动下架）</span></a-radio>
                      <a-radio value="1"> 非版权素材—可生成二维码海报 </a-radio>
                      <a-radio value="0"> 非版权素材-不可生成二维码海报 </a-radio>
                    </a-radio-group>
                    <!-- <span>涉及版权等不可在素材上添加购买二维码的素材，请选择否。</span> -->
                  </a-form-model-item>
                  <a-form-model-item prop="copyrightId" v-if="form.shareState == 3" style="margin-left: 240px">
                    <a-select v-model="form.copyrightId" placeholder="选择版权" class="current">
                      <a-select-option v-for="(item, index) in copyrightList" :key="index" :value="item.id">{{ item.name }}</a-select-option>
                    </a-select>
                  </a-form-model-item>
                  <a-form-model-item label="是否生成单品海报" prop="createProductPoster" v-if="form.shareState == 0">
                    <a-radio-group v-model="form.createProductPoster">
                      <a-radio value="1"> 是 </a-radio>
                      <a-radio value="0"> 否 </a-radio>
                    </a-radio-group>
                    <span>默认生成单品海报，若不想生成单品海报，请选择否。</span>
                  </a-form-model-item>
                </div>
                <a-divider dashed />
                <div id="components-anchor-demo">
                  <h1>关联商品</h1>
                  <a-form-model-item label="关联商品" prop="commodityStatus">
                    <a-radio-group v-model="form.commodityStatus" @change="onChange">
                      <a-radio value="1"> 是 </a-radio>
                      <a-radio value="2"> 否 </a-radio>
                    </a-radio-group>
                    <div v-if="form.commodityStatus == 1">
                      <a-button type="primary" @click="visible = true">添加商品</a-button>
                      <a-table style="margin-top: 20px" :rowKey="record => JSON.stringify(record)" :columns="columns" :data-source="productList" :pagination="false">
                        <span class="product-wrapper" slot="product" slot-scope="item">
                          <img slot="cover" class="img" :src="item.imgurl" :alt="item.value" v-if="item.imgurl" />
                          <img slot="cover" class="img" :alt="item.value" src="https://img.bzhz.jnbygroup.com/cloth.png" v-else />
                          <div class="text">
                            <div class="t">{{ item.value }}&nbsp;&nbsp; &nbsp; {{ item.name }}</div>
                            <div class="t">{{ item.color_name }}</div>
                            <div class="t">¥{{ item.price }}</div>
                          </div>
                        </span>
                        <span slot="action" slot-scope="text, record, index">
                          <div style="display: flex; align-items: center">
                            <a-icon type="file-image" @click="customImg(record, index)" style="margin-right: 5px" />
                            <a-icon type="delete" @click="handleDeleteProduct(index)" />
                          </div>
                        </span>
                        <span slot="price" slot-scope="text, record">
                          <img :src="record.copyrightUrl" style="width: 60px; height: 60px" v-if="record.copyrightUrl" />
                          <span v-else></span>
                        </span>
                      </a-table>
                    </div>
                    <div v-if="form.commodityStatus == 2">
                      <a-form-model-item label="选择素材年份" prop="yearStatus">
                        <a-radio-group v-model="form.yearStatus">
                          <a-radio :value="item" v-for="(item, index) in information.years" :key="index"> {{ item }} </a-radio>
                        </a-radio-group>
                      </a-form-model-item>
                      <a-form-model-item label="选择素材季节" prop="seasonStatus">
                        <a-checkbox-group v-model="form.seasonStatus">
                          <a-checkbox :value="item.key" v-for="item in seasonInfo" :key="item.key"> {{ item.value }} </a-checkbox>
                        </a-checkbox-group>
                      </a-form-model-item>
                    </div>
                  </a-form-model-item>
                </div>
                <a-divider dashed />
                <div id="components-appendix">
                  <h1>附件及使用说明</h1>
                  <div style="width: 240px">
                    <JImageUpload
                      :dowloadTextByName="true"
                      :uploadParams="getUploadParams()"
                      :number="30"
                      :isMultiple="true"
                      :fileSize="10"
                      @fileChange="fileListChange"
                      :listType="'text'"
                      v-model="files"
                      accept="*"
                    ></JImageUpload>
                  </div>
                </div>
              </a-form-model>
            </div>
          </div>
        </div>
        <a-drawer title="商品库" :width="840" :zIndex="4" @close="visible = false" :visible="visible" :destroyOnClose="true">
          <Product :isEmit="true" @add="handleAddProduct" :gender="-1" :allowGetTag="false"></Product>
        </a-drawer>
      </a-spin>
    </a-card>

    <a-button class="record-btn" @click="isaRecord = true" v-if="id && id != 'add'">审核进度</a-button>
    <aRecord v-if="isaRecord" :themeId="themeId" ref="aRecord" @closeRecord="closeRecord"></aRecord>
    <div class="footer-box" v-if="!isCheck">
      <a-button @click="handleBack">取消</a-button>
      <a-button style="margin-left: 8px" @click="preservation" type="primary">发布</a-button>
    </div>
    <a-modal :visible="visibleImg" :destroyOnClose="true" title="自定义商品图片" @cancel="visibleImg = false" @ok="hanleSubmit" centered :width="500">
      <a-form-model ref="rulesForm" :model="obj" :rules="rules" :labelCol="labelCol" :wrapperCol="wrapperCol">
        <a-form-model-item label="图片">
          <JImageUpload :uploadParams="getUploadParams()" :fileSize="2" :accept="'image/*'" :isMultiple="false" @fileChange="fileImage" v-model="imgList"></JImageUpload>
          <div>建议比例1:1，支持jpg, png格式，2M以内</div>
        </a-form-model-item>
      </a-form-model>
    </a-modal>

    <a-modal :visible="tipVisible" :confirm-loading="confirmLoading" @ok="handleConfirm" @cancel="tipVisible = false">
      <p>完成保存后，素材将重新进行审核，是否保存修改？</p>
    </a-modal>
    <!-- <a-modal v-model="frameVisible" width="500px" title="请选择发布方式" okText="确认上架" :confirmLoading="confirmLoading" centered @ok="handleOk" @cancel="handleCancel" :maskClosable="false">
      <a-form layout="vertical" :label-col="{ span: 5 }" :wrapper-col="{ span: 16 }">
        <a-form-item label="发布方式" required>
          <a-radio-group v-model="isShelf">
            <a-radio value="1"> 立即发布 </a-radio>
            <a-radio value="2"> 手动发布 </a-radio>
            <a-radio value="3"> 定时发布 </a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="发布时间" required v-if="isShelf == 3">
          <a-date-picker format="YYYY-MM-DD HH:mm:ss" v-model="putAwayTime" show-time style="width: 200px" />
        </a-form-item>
      </a-form>
    </a-modal> -->
  </div>
</template>
<script>
import aRecord from './components/record'
import moment from 'moment'
import 'moment/locale/zh-cn'

import globalData from '@/assets/js/common'
import { initDictOptions } from '@/components/dict/JDictSelectUtil'
import Product from '@views/box/workbench/fashioner/module/product'
import { themeDetail, publisher, themeDrand, themeEdit, themeClassify, categoryByCode, seasonList, storeVoucher } from '@/api/pos/match'
import Vue from 'vue'
import { USER_INFO } from '@/store/mutation-types'
import JImageUpload from '@/components/qiniuUpload/JImageUpload.vue'
import ImgUpload from './components/JImageUpload.vue'
import List from '../../../../components/AvatarList/List.vue'
import { copyrightList } from '@/api/pos/authority'
import { isNull } from 'mathjs'

const columns = [
  {
    title: '序号',
    customRender: (text, record, index) => `${index + 1}`
  },
  {
    title: '商品',
    scopedSlots: { customRender: 'product' }
  },
  {
    title: '自定义商品图片',
    scopedSlots: { customRender: 'price' }
  },
  {
    title: '操作',
    scopedSlots: { customRender: 'action' }
  }
]
export default {
  components: {
    JImageUpload,
    Product,
    ImgUpload,
    List,
    aRecord
  },
  data() {
    let validateBrand = (rule, value, callback) => {
      conosle.log(value, '品牌')
      if (this.brandId && this.brandId.length < 1) {
        callback(new Error('请选择适用品牌'))
      } else {
        callback()
      }
    }
    return {
      endOpen: false,
      spinning: false,
      columns,
      obj: {
        imgList: ''
      },
      currentEditIndex: '',
      imgList: [],
      visibleImg: false,
      seasonInfo: [],
      confirmLoading: false,
      id: this.$route.params.id,
      isShelf: '0',
      coverUrl: '',
      videoUrl: '',
      putAwayTime: null,
      labelCol: { span: 3 },
      wrapperCol: { span: 18 },
      visible: false,
      tipVisible: false, // 提示框
      frameVisible: false,
      productList: [],
      publisher: [],
      barandList: [],
      classifyList: [],
      leafClassifyList: [],
      copyList: [],

      informationlist: [
        { title: '基本信息', herf: '#components' },
        { title: '投放信息', herf: '#components-throw' },
        { title: '上传图像', herf: '#components-anchor' },
        { title: '关联商品', herf: '#components-anchor-demo' },
        { title: '上传附件', herf: '#components-appendix' }
      ],
      form: {
        name: '',
        content: '',
        storeType: '1',
        publisherId: '',
        cation: undefined,
        brandId: [],
        putChannel: ['1', '2'],
        putStoreType: [],
        backgroundImage: [],
        videoList: [],
        shareState: '',
        createProductPoster: null,
        commodityStatus: '1',
        yearStatus: '',
        seasonStatus: [],
        classification: undefined,
        copyrightId: '',
        putAwayType: '1', //
        finishTime: '1',
        putAwayEndTime: '',
        putAwayTime: '',
        storePkgId: null,
        files: []
      },
      backgroundImage: [],
      fileSizeList: [],
      videoList: [],
      rules: {
        name: [
          { required: true, message: '请填写标题', trigger: 'blur' },
          { max: 50, message: '标题长度限制50字内', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请填写介绍', trigger: 'blur' },
          { max: 200, message: '介绍文案长度限制200字内', trigger: 'blur' }
        ],
        publisherId: [{ required: true, message: '请选择发布方', trigger: 'blur' }],
        cation: [{ required: true, message: '请选择分类', trigger: 'blur' }],
        putChannel: [
          {
            type: 'array',
            required: true,
            message: '请选择可见渠道',
            trigger: 'change'
          }
        ],
        shareState: [{ required: true, message: '请选择是否生成海报', trigger: 'change' }],
        storeType: [{ required: true, message: '请选择投放门店', trigger: 'blur' }],
        putAwayType: [{ required: true, message: '请选择投放开始时间', trigger: 'blur' }],
        finishTime: [{ required: true, message: '请选择投放结束时间', trigger: 'blur' }],
        copyright: [{ required: true, message: '请选择版权', trigger: 'blur' }],
        createProductPoster: [{ required: true, message: '请选择单品海报', trigger: 'change' }],
        commodityStatus: [{ required: true, message: '请选择商品', trigger: 'change' }],
        yearStatus: [{ required: true, message: '请选择素材年份', trigger: 'change' }],
        seasonStatus: [{ required: true, message: '请选择素材季节', trigger: 'change' }],

        brandId: [{ required: true, validator: validateBrand, trigger: 'blur' }]
      },
      moment,
      adverId: '',
      tags: [],
      brandId: [],
      beginDate: '',
      record: '',
      endDate: '',
      // fileList: [],
      advertLoc: [],
      advertJumpUrl: [],
      tipsImg: false,
      information: {},
      userInfo: Vue.ls.get(USER_INFO),
      copyInfo: null,
      copyrightList: [],
      isaRecord: false,
      themeId: '',
      isCheck: false,
      storeList: [],
      files: []
    }
  },
  async mounted() {
    if (this.id && this.id != 'add') {
      if (this.id.includes('detail')) {
        this.isCheck = true
        this.id = this.id.substring(0, this.id.length - 6)
      }
    }
    this.postSeasonList() // 季节
    this.postPublisher() // 发布方
    this.postThemeDrand() // 品牌
    this.getCopyrightList() // 版权
    this.getStore() // 门店包
    await this.postThemeClassify() // 分类
    await this.postDetail()
  },
  created() {
    this.initDictConfig()
  },

  beforeRouteLeave(to, from, next) {
    this.$destroy()
    next()
  },
  watch: {},
  methods: {
    onChangeSTime(date, dateString) {
      this.form.putAwayTime = dateString
    },
    onChangeETime(date, dateString) {
      if (this.form.putAwayTime) {
        let begin = new Date(this.form.putAwayTime.replace(/-/g, '/'))
        let end = new Date(dateString.replace(/-/g, '/'))
        if (begin - end > 0) {
          this.$message.error('投放结束时间不能早于开始时间')
          this.form.putAwayEndTime = null
          return
        } else {
          // this.form.putAwayEndTime = dateString
          this.form.putAwayEndTime = dateString.split(':')[0]
        }
      } else {
        this.form.putAwayEndTime = dateString.split(':')[0]
      }
      console.log(this.form.putAwayEndTime, 'this.form.putAwayEndTime')
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    getStore() {
      const params = {
        isStorePackage: true
      }
      storeVoucher(params).then(res => {
        if (res.code == 200) {
          this.storeList = res.data
          this.storeList.forEach(ele => {
            ele.storeName = `SD${ele.packageId} ${ele.packageName}`
          })
          console.log(this.storeList, ' this.storeList')
        } else {
          // this.$message.warning(res.msg)
        }
      })
    },
    closeRecord() {
      this.isaRecord = false
    },
    // 获取版权
    async getCopyrightList() {
      const param = {
        current: 1,
        size: 100,
        status: 'Y'
      }
      const res = await copyrightList(param)
      if (res.code == 200) {
        this.copyrightList = res.data.records
      } else {
        this.$message.error(res.msg || res.message)
      }
    },
    onChange() {
      if (this.form.commodityStatus == '1') {
        this.form.yearStatus = ''
        this.form.seasonStatus = ''
      }
      if (this.form.commodityStatus == '2') {
        this.productList = []
      }
    },
    postThemeClassify() {
      let params = {
        channelType: 'retailTheme'
      }
      return themeClassify(params).then(res => {
        if (res.code == 200) {
          this.classifyList = res.data.classifyList
          this.leafClassifyList = res.data.leafClassifyList
          return res
        } else {
          // this.$message.warning(res.msg)
        }
      })
    },
    hanleSubmit() {
      this.productList[this.currentEditIndex].copyrightUrl = this.obj.imgList && this.obj.imgList.length > 0 ? this.obj.imgList : ''

      this.visibleImg = false
    },
    // 回显
    postDetail() {
      this.spinning = true
      let data = {
        themeId: this.id == 'add' ? '' : this.id,
        workNo: this.$store.getters.userInfo.workNo
      }
      this.themeId = Number(this.id)
      themeDetail(data).then(res => {
        if (res.code == 200) {
          this.spinning = false
          console.log(res.data, '回显')
          this.information = res.data
          let data = res.data

          let brandIdsList = data.brandIds ? data.brandIds.split(',') : []
          let publisherIdsList = data.publisherIds ? data.publisherIds.split(',') : []
          this.copyIdList = data.classifyIds ? data.classifyIds.split(',') : []
          let classifyIdsList = this.copyIdList.map(item => {
            return item.substring(0, 11)
          })
          this.tags = this.tags.filter(item => brandIdsList.includes(item.key))
          this.classifyList = this.classifyList.filter(item => classifyIdsList.includes(item.code))
          this.publisher = this.publisher.filter(item => publisherIdsList.includes(item.key))

          if (this.id && this.id != 'add') {
            this.form.name = data.name //标题
            this.form.content = data.content //介绍
            this.form.publisherId = data.publisherId // 发布方
            this.pubCopy(data.publisherId, data.publisherName)
            this.productList = data.themeDetails //商品
            this.brandId = data.brandId ? data.brandId.split(',') : [] // 品牌
            this.form.putChannel = data.posThemeExt.putChannel == 0 ? ['1', '2'] : data.posThemeExt.putChannel == 1 ? ['1'] : data.posThemeExt.putChannel == 2 ? ['2'] : [] // 可见渠道
            this.form.putStoreType = data.posThemeExt.putStoreType ? data.posThemeExt.putStoreType.split(',') : [] // 不可见门店
            this.backgroundImage = data.backgroundImage ? data.backgroundImage.split(',') : [] // 海报
            this.form.putAwayType = data.putAwayType.toString()
            this.form.putAwayTime = data.putAwayType == 3 ? data.putAwayTime : null
            console.log(data.putAwayEndTime, 'data.putAwayEndTime')
            this.form.finishTime = data.putAwayEndTime == '9999-12-30 23:59:59' ? '1' : '2'
            this.form.putAwayEndTime = data.putAwayEndTime == '9999-12-30 23:59:59' ? '' : data.putAwayEndTime
            this.form.storeType = data.posThemeExt.storeType.toString()
            this.form.storePkgId = data.posThemeExt.storePkgId
            this.files = data.posThemeExt.files.map(item => {
              let info = {
                url: item.fileUrl,
                name: item.fileName
              }
              return info
            })

            this.videoList = data.videoDetail.videoUrl ? data.videoDetail.videoUrl.split(',') : '' // 视频
            if (data.posThemeExt.shareState == 0) {
              this.form.createProductPoster = data.posThemeExt.createProductPoster.toString() // 单品海报
            }
            this.form.shareState = data.posThemeExt.shareState.toString() // 海报
            this.form.commodityStatus = data.posThemeExt.themeSeasons ? '2' : '1' // 是否关联商品
            this.form.classification = data.classifyId // 分类
            if (data.productNum == 0) {
              this.productList = []
            } else {
              this.productList = data.themeDetails.map(item => {
                let product = {
                  id: item.productId,
                  value: item.productName,
                  name: item.productNo,
                  productSize: '',
                  colorno: item.productColor,
                  color_name: item.productColorName,
                  price: item.productPrice,
                  productBrand: '',
                  productYear: '',
                  productBand: '',
                  small_season: item.productSeason,
                  sku: '',
                  skuId: '',
                  imgurl: item.imgUrl,
                  sortNum: '',
                  createTime: '',
                  updateTime: '',
                  colorCount: '',
                  storeStock: '',
                  ebStock: '',
                  year: item.year,
                  copyrightUrl: item.copyrightUrl
                }
                return product
              }) // 商品
            }
            this.form.seasonStatus = data.posThemeExt.themeSeasons.split(',') // 素材年份
            this.form.yearStatus = Number(data.posThemeExt.themeYear) // 素材季节

            let copyInfo = {
              name: data.classifyName,
              code: data.classifyId
            }

            // 海报——使用版权id
            if (data.posThemeExt.shareState == 3) {
              this.form.copyrightId = data.posThemeExt.copyrightId
              this.form.copyrightName = data.posThemeExt.copyrightName
              let isCopyRight = this.copyrightList.some(item => item.id == this.form.copyrightId)
              if (!isCopyRight) {
                this.copyrightList.push({
                  id: this.form.copyrightId,
                  name: this.form.copyrightName
                })
              }
            }
            this.goryByCode(data.classifyId, copyInfo)
          }
        } else {
          // this.$message.warning(res.msg)
          this.spinning = false
        }
      })
    },
    pubCopy(publisherId, publisherName) {
      let flag = this.publisher.some(item => item.key == publisherId)
      console.log(flag, 'flag')
      if (!flag) {
        this.publisher.push({
          key: publisherId,
          value: publisherName
        })
      }
    },
    handleProvinceChange(value) {
      let list = this.leafClassifyList.filter(item => item.pidCode == value)
      this.copyList = list.filter(item => this.copyIdList.includes(item.code))
      this.form.cation = null
    },
    goryByCode(code, copyInfo) {
      categoryByCode(code).then(res => {
        let type = this.classifyList.some(item => item.code == res.pidCode)
        console.log(!type, 'type')
        if (!type) {
          this.classifyList.push({
            name: res.pidName,
            code: res.pidCode
          })
        }
        let data = copyInfo
        data.pidCode = res.pidCode
        console.log(this.leafClassifyList, ' this.leafClassifyList')
        let flag = this.leafClassifyList.some(item => item.code == code)
        if (!flag) {
          this.leafClassifyList.push(data)
        }
        this.form.classification = res.pidCode
        this.copyList = this.leafClassifyList.filter(item => item.pidCode == res.pidCode)
        // 筛选
        if (this.id && this.id != 'add') {
          this.copyList = this.copyList.filter(item => this.copyIdList.includes(item.code))
        }
        this.form.cation = code
      })
    },
    async postThemeClassify() {
      let params = {
        channelType: 'retailTheme'
      }
      await themeClassify(params).then(res => {
        if (res.code == 200) {
          this.classifyList = res.data.classifyList
          this.leafClassifyList = res.data.leafClassifyList
        } else {
          // this.$message.warning(res.msg)
        }
      })
    },
    postSeasonList() {
      seasonList().then(res => {
        console.log(res, '季节')
        if (res.code == 200) {
          this.seasonInfo = res.data
        } else {
          // this.$message.warning(res.msg)
        }
      })
    },

    postPublisher() {
      publisher().then(res => {
        if (res.code == 200) {
          this.publisher = res.data
        } else {
          // this.$message.warning(res.msg)
        }
      })
    },
    postThemeDrand() {
      themeDrand().then(res => {
        if (res.code == 200) {
          this.tags = res.data
        } else {
          // this.$message.warning(res.msg)
        }
      })
    },

    postThemeDetail() {
      let data = {
        workNo: this.$store.getters.userInfo.workNo
      }
      themeDetail(data).then(res => {
        if (res.code == 200) {
          this.information = res.data
        } else {
          // this.$message.error(res.msg || res.message)
        }
      })
    },
    anchorClick(e) {
      e.preventDefault()
    },
    gerGood() {
      return document.getElementById('goods')
    },
    handleAddProduct(v) {
      v.copyrightUrl = ''
      let ids = this.productList.map(e => e.id + e.colorno)
      if (ids.includes(v.id + v.colorno)) {
        this.$message.error('不可重复添加相同的商品！')
        return
      }
      this.productList.push(v)
    },
    customImg(record, index) {
      this.currentEditIndex = index
      if (record.copyrightUrl) {
        this.imgList = record.copyrightUrl
      }

      this.visibleImg = true
    },
    handleDeleteProduct(index) {
      this.productList.splice(index, 1)
    },
    handleChange(tag, checked) {
      const { brandId } = this
      const nextSelectedTags = checked ? [...brandId, tag] : brandId.filter(t => t !== tag)
      this.brandId = nextSelectedTags
    },
    fileImageChange(list) {
      this.form.backgroundImage = list.map(item => item.url)
    },
    fileImage(list) {
      this.obj.imgList = list.length > 0 ? list[0].url : []
    },
    fileListChange(list) {
      this.form.files = list.map(item => {
        const newItem = {
          fileName: item.name,
          fileUrl: item.url
        }
        return newItem
      })
    },
    fileVideoChange(list) {
      this.form.videoList = list
      this.coverUrl = list.map(item => item.url)
      this.coverUrl = this.coverUrl.map(item => {
        return `${item}?vframe/jpg/offset/1`
      })
      this.videoUrl = list.map(item => item.url) // 视频url
    },

    // 初始化字典
    initDictConfig() {
      //初始化字典 - 广告位
      initDictOptions('advert_loc').then(res => {
        if (res.success) {
          this.advertLoc = res.result
        }
      })
      initDictOptions('advert_jump_url').then(res => {
        if (res.success) {
          this.advertJumpUrl = res.result
        }
      })
    },
    // 上传图片
    getUploadParams() {
      return {
        ...globalData.uploadParams
      }
    },
    // fileChange(list) {
    //   this.fileList = list
    // },
    handleBack() {
      this.$router.back()
    },
    handleConfirm() {
      this.spinning = false
      // if (this.isShelf == 3 && !this.putAwayTime) {
      //   this.$message.error('请选择发布时间！')
      //   return
      // }

      this.tipVisible = false
      let themeDetails = this.productList.map(item => {
        let theme = {
          id: '',
          themeId: '',
          productId: item.id,
          productName: item.value,
          productNo: item.name,
          productSize: '',
          productColor: item.colorno,
          productColorName: item.color_name,
          productPrice: item.price,
          productBrand: '',
          productYear: '',
          productBand: '',
          productSeason: item.small_season,
          sku: '',
          skuId: '',
          imgUrl: item.imgurl,
          sortNum: '',
          createTime: '',
          updateTime: '',
          colorCount: '',
          storeStock: '',
          ebStock: '',
          year: item.year,
          copyrightUrl: item.copyrightUrl
        }
        return theme
      })

      let type = this.form.putChannel.toString()
      let putChannel = type == '1' ? 1 : type == '2' ? 2 : 0
      let classList = this.copyList.filter(item => item.code == this.form.cation)

      let publisherName = this.publisher.filter(item => item.key == this.form.publisherId)

      let posThemeExt = {
        storeType: Number(this.form.storeType),
        storePkgId: this.form.storePkgId,
        // files: this.form.files,
        putChannel: this.form.storeType == 2 ? '' : putChannel, //可见渠道
        putStoreType: this.form.putStoreType.toString(), //不可见门店
        shareState: this.form.shareState, //海报
        createProductPoster: this.form.shareState == 1 ? '1' : this.form.createProductPoster, // 单品海报
        themeSeasons: this.form.seasonStatus && this.form.seasonStatus.length > 0 ? this.form.seasonStatus.toString() : '', // 季节
        themeYear: this.form.yearStatus, //年份
        copyrightId: this.form.shareState == '3' ? this.form.copyrightId : ''
      }
      if (this.form.files && this.form.files.length > 0) {
        posThemeExt.files = this.form.files
      }

      let videoDetail = {
        coverUrl: this.coverUrl.toString(),
        videoUrl: this.videoUrl.toString()
      }
      console.log(videoDetail, 'videoDetail')
      let params = {}
      let timestamp = moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
      console.log(timestamp, 'timestamp')
      params = {
        putAwayType: Number(this.form.putAwayType),
        putAwayTime: this.form.putAwayType == 1 ? timestamp : this.form.putAwayTime.split(':')[0] + ':00:00',
        putAwayEndTime: this.form.finishTime == 1 ? '9999-12-30 23:59:59' : this.form.putAwayEndTime + ':00:00',
        backgroundImage: this.form.backgroundImage, // 海报图
        themeDetails: themeDetails, // 商品
        name: this.form.name, //	标题
        content: this.form.content, //	简介
        brandId: this.brandId.toString(),
        posThemeExt: posThemeExt,
        publisherId: this.form.publisherId, // 发布方ID
        publisherName: publisherName.length > 0 ? publisherName[0].value : '', // 发布方名字
        channelType: 'B10-A02', // 一级分类
        classifyId: this.form.cation, // 二级分类id
        classifyName: classList.length > 0 ? classList[0].name : '', // 二级分类名称
        workNo: this.userInfo.workNo, // 审核人工号
        realname: this.userInfo.realname, // 审核人
        isShelf: '0' // 发布方式
      }

      if (this.id && this.id != 'add') {
        params.id = this.id
      }
      if (videoDetail.videoUrl) {
        params.videoDetail = videoDetail
      }
      console.log(params, 'params')
      themeEdit(params).then(res => {
        this.confirmLoading = false
        if (res.code == 200) {
          this.$message.success('成功')
          this.$router.push('/pos+/match/collocation/list')
        } else {
          this.$message.error(res.msg || res.message)
        }
      })
    },
    handleCancel() {
      // this.frameVisible = true
      this.putAwayTime = ''
    },
    // 编辑提示
    // handleConfirm() {
    //   this.tipVisible = false
    //   // this.frameVisible = true
    // },
    preservation() {
      // this.spinning = true
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          if (!this.brandId.length) {
            this.$message.error('请选择适用品牌！')
            return
          }
          if (this.form.storeType == 2 && !this.form.storePkgId) {
            this.$message.error('请选择门店包！')
            return
          }
          if (this.form.putAwayType == 3 && !this.form.putAwayTime) {
            this.$message.error('请设置投放开始时间！')
            return
          }
          if (this.form.finishTime == 2 && !this.form.putAwayEndTime) {
            this.$message.error('请设置投放结束时间！')
            return
          }

          if (this.form.shareState == 3 && !this.form.copyrightId) {
            this.$message.error('请选择版权')
            return
          }
          if (!this.form.backgroundImage.length && !this.form.videoList.length) {
            this.$message.error('请上传海报图或者视频！')
            return
          }

          if (this.form.commodityStatus == 1) {
            if (!this.productList.length) {
              this.$message.error('请添加商品！')
              return
            }
          }
          if (this.form.finishTime == 2 && this.form.putAwayTime && this.form.putAwayEndTime) {
            let begin = new Date(this.form.putAwayTime.replace(/-/g, '/'))
            console.log(begin, 'begin')
            let end = new Date(this.form.putAwayEndTime.replace(/-/g, '/'))

            if (begin - end > 0) {
              this.$message.error('投放结束时间不能早于开始时间')
              this.form.putAwayEndTime = null
              return
            }
          }

          // 编辑保存提示
          if (this.id && this.id != 'add') {
            this.tipVisible = true
          } else {
            this.handleConfirm()
            this.spinning = true
          }
          //  else {
          //   this.frameVisible = true
          // }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    application() {}
  }
}
</script>
<style scoped lang="less">
/deep/ .ant-tag-checkable {
  border: 1px solid #ccc;
}
.current {
  width: 220px;
}
.edit-title {
  width: 120px;
  color: #333;
  font-size: 14px;
  font-weight: 700;
  cursor: pointer;
  border-right: 1px solid #ccc;
  margin-right: 16px;
}
.brand-box {
  display: flex;
}
.sign {
  margin-right: 12px;
}

.icon-img {
  width: 86px;
  height: 86px;
  object-fit: scale-down;
}

.tip {
  color: #f5222d;
  line-height: 22px;
  margin-top: -8px;
}
.product-wrapper {
  display: flex;
  .img {
    display: block;
    width: 60px;
    height: 60px;
    border: 1px dashed #f5f5f5;
    object-fit: scale-down;
  }
  .text {
    flex: 1;
    margin-left: 10px;
    line-height: 20px;
    font-size: 12px;
    color: #333;
    min-width: 240px;
    .t {
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 1;
      word-break: break-all; /* 追加这一行代码 */
      /* autoprefixer: off */
      -webkit-box-orient: vertical;
      /* autoprefixer: on */
    }
  }
}
.footer-box {
  font-size: 14px;
  font-weight: 500;
  box-shadow: 0 -1px 6px rgba(0, 0, 0, 0.1);
  position: relative;
  background-color: #fff;
  height: 60px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
.edit-font {
  color: #7f7f7f;
  margin-left: 24px;
}
/deep/ .ant-anchor-ink::before {
  background-color: transparent;
}
.record-btn {
  position: absolute;
  right: 55px;
  top: 30%;
  width: 46px;
  height: 100px;
  white-space: pre-wrap;
  text-align: center;
}
</style>
